package com.zzyl.nursing.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.framework.config.properties.WechatProperties;
import com.zzyl.nursing.service.WechatService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Map;

@RequiredArgsConstructor
@Service
public class WechatServiceImpl implements WechatService {

    private final WechatProperties wechatProperties;

    // 获取微信openId
    @Override
    public String getOpenId(String code) {
        Map<String, Object> paramMap = MapUtil.<String, Object>builder()
                .put("appid", wechatProperties.getAppId())
                .put("secret", wechatProperties.getAppSecret())
                .put("js_code", code)
                .put("grant_type", "authorization_code")
                .build();
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        String resJson = HttpUtil.get(url, paramMap);
        JSONObject parseObj = JSONUtil.parseObj(resJson);
        if (parseObj.containsKey("errcode")) {
            throw new ServiceException("请求微信服务器失败");
        }
        return parseObj.getStr("openid");
    }

    // 获取微信accessToken
    @Override
    public String getAccessToken() {
        Map<String, Object> paramMap = MapUtil.<String, Object>builder()
                .put("appid", wechatProperties.getAppId())
                .put("secret", wechatProperties.getAppSecret())
                .put("grant_type", "client_credential")
                .build();
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        String resJson = HttpUtil.get(url, paramMap);
        JSONObject parseObj = JSONUtil.parseObj(resJson);
        if (parseObj.containsKey("errcode")) {
            throw new ServiceException("请求微信服务器获取access_token失败");
        }
        return parseObj.getStr("access_token");
    }

    // 获取微信手机号
    @Override
    public String getPhoneNumber(String accessToken, String phoneCode, String openId) {
        Map<String, Object> paramMap = MapUtil.<String, Object>builder()
                .put("code", phoneCode)
                .put("openid", openId)
                .build();
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+accessToken;
        String resJson = HttpUtil.post(url, JSONUtil.toJsonStr(paramMap));
        JSONObject parseObj = JSONUtil.parseObj(resJson);
        if (!parseObj.getInt("errcode").equals(0)) {
            throw new ServiceException("请求微信服务器获取手机号失败"+parseObj.getStr("errmsg"));
        }
        return parseObj.getJSONObject("phone_info").getStr("phoneNumber");
    }
}
